package org.jeecg.modules.inspect.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.constant.CommonSendStatus;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.inspect.entity.InsPoint;
import org.jeecg.modules.inspect.entity.InsTask;
import org.jeecg.modules.inspect.entity.InsTaskItem;
import org.jeecg.modules.inspect.entity.InsTaskRecord;
import org.jeecg.modules.inspect.mapper.InsPointMapper;
import org.jeecg.modules.inspect.mapper.InsTaskItemMapper;
import org.jeecg.modules.inspect.mapper.InsTaskMapper;
import org.jeecg.modules.inspect.mapper.InsTaskRecordMapper;
import org.jeecg.modules.inspect.service.IInsTaskRecordService;
import org.jeecg.modules.inspect.util.SmsUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 任务记录
 * @Author: jeecg-boot
 * @Date:   2023-11-24
 * @Version: V1.0
 */
@Service
public class InsTaskRecordServiceImpl extends ServiceImpl<InsTaskRecordMapper, InsTaskRecord> implements IInsTaskRecordService {

    @Resource
    private ISysBaseAPI sysBaseApi;
    @Resource
    private InsPointMapper insPointMapper;
    @Resource
    private InsTaskItemMapper insTaskItemMapper;
    @Resource
    private InsTaskMapper insTaskMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMulti(InsTaskRecord insTaskRecord) {
        String taskId = insTaskRecord.getTaskId();
        String cardNo = insTaskRecord.getCardNo();
        String insStatus = insTaskRecord.getInsStatus();

        if(StrUtil.isBlank(taskId)) {
            // 无任务巡检

        } else {
            // 任务巡检:更新任务项状态、更新任务状态
            InsTaskItem taskItem = insTaskItemMapper.selectById(insTaskRecord.getItemId());
            taskItem.setItemStatus("2");
            taskItem.setInsTime(new Date());
            insTaskItemMapper.updateById(taskItem);

            InsTask insTask = insTaskMapper.selectById(insTaskRecord.getTaskId());
            //查询全部巡检任务项记录
            List<InsTaskItem> insTaskItems = insTaskItemMapper.selectList(Wrappers.<InsTaskItem>lambdaQuery()
                    .eq(InsTaskItem::getTaskId, insTaskRecord.getTaskId())
                    /*.eq(InsTaskItem::getItemStatus, "1")*/
            );
            if(CollectionUtils.isEmpty(insTaskItems)){
                insTaskItems = new ArrayList<>();
            }
            //已巡检
            List<InsTaskItem> inspectedList = insTaskItems.stream().filter(o -> "2".equals(o.getItemStatus())).collect(Collectors.toList());
            //未巡检
            List<InsTaskItem> notInspectedList = insTaskItems.stream().filter(o -> "1".equals(o.getItemStatus())).collect(Collectors.toList());
            //已巡检数
            insTask.setInspectedNum(CollectionUtils.isNotEmpty(inspectedList)?inspectedList.size():0);
            //不存在未巡检 改变主表状态为3：已巡检
            if(CollectionUtils.isEmpty(notInspectedList)){
                insTask.setTaskStatus("3");
            }else{
                insTask.setTaskStatus("2");
            }
            insTaskMapper.updateById(insTask);

            // int inspectedNum = insTask.getInspectedNum() + 1;
//            int inspectedNum = insTaskItems.size();
//            insTask.setInspectedNum(insTaskItems.size());
//
//            if(insTask.getPointNum().intValue() == inspectedNum) {
//                insTask.setTaskStatus("3");
//            } else {
//                insTask.setTaskStatus("2");
//            }
//            insTaskMapper.updateById(insTask);
        }

        InsPoint insPoint = insPointMapper.selectById(insTaskRecord.getPointId());

        if(StrUtil.isBlank(cardNo)) {
            // 无卡号,卡异常，推送消息
            List<String> userNames = sysBaseApi.queryUserByRoleCode("admin");
            String receiver = String.join(",",userNames.stream().map(String::valueOf).collect(Collectors.toList()));

            try {
                MessageDTO md = new MessageDTO();
                md.setFromUser("system");
                md.setToAll(false);
                md.setTitle("卡识别异常");
                md.setTemplateCode(CommonSendStatus.CARD_EXCEPTION);
                md.setToUser(receiver);
                md.setType("system");
                Map<String, Object> data = new HashMap<>();
                data.put("pointName", insPoint.getPointName());
                md.setData(data);
                sysBaseApi.sendTemplateMessage(md);

            } catch (Exception e) {
                e.printStackTrace();
                log.error("发送消息出错" + e.getMessage());
            }

        } else {

        }
        // 异常发送短信
        if(StrUtil.isNotEmpty(insStatus)) {
            if(insStatus.equals("2")) {
                String userPhone = insTaskRecord.getUserPhone();
                if(StrUtil.isNotEmpty(userPhone)) {
                    String smsContent = "点位：" + insPoint.getPointName() + "巡检异常，备注：" + insTaskRecord.getRemark();
                    try{
                        // 发送巡检异常短信提醒 注释发送短信代码
                        SmsUtil.sendMas(new String[]{ userPhone }, smsContent);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                }
            }
        }

        return SqlHelper.retBool(this.baseMapper.insert(insTaskRecord));
    }

    /**
     * 根据登录用户查询
     * @param page
     * @param createBy 用户账户名称
     * @return
     */
    @Override
    public IPage<InsTaskRecord> mList(Page<InsTaskRecord> page, InsTaskRecord insTaskRecord) {
        return this.baseMapper.mList(page, insTaskRecord);
    }

    @Override
    public IPage<InsTaskRecord> findListPage(Page<InsTaskRecord> page, InsTaskRecord record) {
        return this.baseMapper.findListPage(page, record);
    }

}
